<?php

namespace app\webapi\vms\service\cms;

use app\webapi\common\BaseService;
use app\webapi\vms\model\ArticleContentModel;
use app\webapi\vms\model\ArticleModel;
use app\webapi\vms\model\ChannelModel;
use library\OWException;
use think\facade\Db;
use think\facade\Log;

/**
 * @文章服务类
 */
class ProductService extends BaseService
{
    /**
     * @desc 获取产品分页列表
     * @param $page_no
     * @param $page_size
     * @param $website_id
     * @param $category_id
     * @param $keyword
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     * @author zhaozhiwei
     * @time 2023/12/11-11:43
     */
    public function getPaginateList($page_no, $page_size, $website_id, $category_id, $keyword)
    {
        //组装查询条件
        $where = ['delete_time' => 0, 'root_pid' => 4];
        if ($category_id != '') {
            //验证分类id是否存在
            $category_id = ChannelModel::where(['website_id' => $website_id, 'id' => $category_id])
                ->value('id');
            if (!$category_id) {
                throw (new OWException('分类id不存在', `站点id${website_id}:下分类id${category_id}不存在`));
            }
        }

        //定义查询参数
        $fields = ['id', 'release_time', 'status', 'cover', 'title', 'sort', 'reading_volume', 'channel_id'];

        //过滤查询关键字的空格
        $keyword = str_replace(' ', '', $keyword);
        //查询分页数据
        $list = ArticleModel::suffix($website_id)->field($fields)->append(['status_text'])
            ->where($where)
            ->whereLike('title', '%' . $keyword . '%')
            ->order('create_time','desc')
            ->paginate(['page' => $page_no, 'list_rows' => $page_size]);

        //获取列表中分类id数组
        $category_id_arr = array_column($list->items(), 'channel_id');
        //查询分类名称
        $category_names_kv_list = ChannelModel::where(['id' => $category_id_arr])->column('name', 'id');

        //处理数据
        foreach ($list->items() as &$v) {
            $v['channel_name'] = $category_names_kv_list[$v['channel_id']] ?? '';
        }
        unset($v);
        return $list;
    }

    /**
     * @desc 编辑产品
     * @param $params
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/11-11:43
     */
    public function edit($params, $website_id)
    {
        //查询产品分类信息
        $where = ['delete_time' => 0, 'id' => $params['channel_id'], 'website_id' => $website_id];
        $category_info = ChannelModel::field(['id', 'root_pid'])
            ->where($where)->find();
        //检测栏目id是否是产品栏目
        if ($category_info['root_pid'] != 4) {
            throw new OWException('该分类不是产品分类', $category_info['root_pid']);
        }

        $articleModel = ArticleModel::suffix($website_id);
        //检测产品名是否重复
        $where = ['title' => $params['title'], 'website_id' => $website_id];
        $product = ArticleModel::suffix( $website_id)->field(['id'])->where($where)->find();
        if (!empty($product) && isset($params['id'])) {
            throw new OWException('产品名重复', $params['title']);
        }

        $params['root_pid'] = 4;
        $contentModel = (new ArticleContentModel())->setSuffix($website_id);
        try {
            //启动事务
            Db::startTrans();

            if (isset($params['id']) && !empty($params['id']) && $params['id'] != '') {
                //编辑数据
                $content_data=['content' => $params['content'],'article_id'=>$params['id']];
                if (isset($params['content'])) {
                    $contentModel->where(['article_id' => $params['id']])->save($content_data);
                }
                unset($params['content']);
                $articleModel->setSuffix($website_id)->where(['id' => $params['id']])->save($params);
            } else {
                $params['id']=$this->createSnowId();
                //写入数据
                $content_data=['content' => $params['content'],'article_id'=>$params['id']];
                $contentModel->save($content_data);
                unset($params['content']);
                $articleModel->setSuffix($website_id)->save($params);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new OWException('操作失败', $e->getMessage());
        }

        return true;
    }

    /**
     * @desc 获取产品详情
     * @return mixed
     * @author zhaozhiwei
     * @time 2023/12/11-11:43
     */
    public function getInfo($id, $website_id)
    {
        //定义查询字段
        $field = ['id', 'title', 'cover', 'channel_id', 'website_id', 'release_time', 'tags', 'status', 'reading_volume',
            'seo_title', 'seo_keywords', 'seo_desc', 'is_show_index', 'is_show_list', 'imgs'];
        //查询案例信息
        $info = ArticleModel::suffix($website_id)->field($field)
            ->append(['is_show_index_text', 'is_show_list_text', 'status_text'])
            ->where(['id' => $id, 'website_id' => $website_id])->find();
        if (empty($info)) {
            throw (new OWException('产品不存在', $id));
        }
        //查看权限
        if ($info['website_id'] != $website_id) {
            throw (new OWException('没有权限', $id));
        }
        //查询栏目名称
        $info['category_id'] = $info['channel_id'];
        unset($info['category_id']);
        $info['category_name'] = ChannelModel::where(['id' => $info['category_id']])->value('name');

        //转换tags数据格式
        $tags_arr = explode(',', $info['tags']);
        $tags_show_arr = [];
        foreach ($tags_arr as $key => $v) {
            array_push($tags_show_arr, ['id' => $key + 1, 'title' => $v]);
        }
        //转换imgs数据格式
        $img_arr = explode(',', $info['imgs']);
        $img_show_arr = [];
        foreach ($img_arr as $key => $v) {
            array_push($img_show_arr, ['id' => $key + 1, 'title' => $v]);
        }
        $info['tags_arr'] = $tags_show_arr;
        $info['img_arr'] = $img_show_arr;
        //隐藏敏感、冗余数据
        unset($info['website_id'], $info['channel_id'], $info['tags'], $info['imgs']);
        $info['content'] = ArticleContentModel::suffix($website_id)->where(['article_id' => $info['id']])->value('content');
        return $info;
    }

    /**
     * @desc 删除产品
     * @param $id_arr
     * @param $website_id
     * @return array
     * @author zhaozhiwei
     * @time 2023/12/11-11:57
     */
    public function delete($id_arr, $website_id)
    {
        $product_id_arr = ChannelModel::where(['id' => $id_arr, 'website_id' => $website_id])->column('id');
        ArticleModel::suffix($website_id)->where(['id' => $product_id_arr])->update(['delete_time' => time()]);
        Log::record('被删除的案例id集合:' . implode(',', $product_id_arr));
        return ['name' => '被删除的id数组', 'list' => $product_id_arr];
    }

}